package com.corgi.quartz.config;

import com.corgi.quartz.job.QuartzJob;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @title: QuartzConfig
 * @description:
 * @author: dengmiao
 * @create: 2019-11-11 14:41
 **/
@Configuration
public class QuartzConfig {

    /**
     * 1、创建job对象
     */
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean() {
        JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
        // 关联自定义job类
        jobDetailFactory.setJobClass(QuartzJob.class);
        return jobDetailFactory;
    }

    /**
     * 2、创建trigger对象
     * 简单trigger
     */
    @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactory) {
        SimpleTriggerFactoryBean simpleTriggerFactory = new SimpleTriggerFactoryBean();
        // 关联jobDetail对象
        simpleTriggerFactory.setJobDetail(jobDetailFactory.getObject());
        // 执行的毫秒数
        simpleTriggerFactory.setRepeatInterval(2000);
        // 重复次数
        simpleTriggerFactory.setRepeatCount(5);
        return simpleTriggerFactory;
    }

    /**
     * cron trigger
     */
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactory) {
        CronTriggerFactoryBean cronTriggerFactory = new CronTriggerFactoryBean();
        // 关联jobDetail对象
        cronTriggerFactory.setJobDetail(jobDetailFactory.getObject());
        // 设置触发时间
        cronTriggerFactory.setCronExpression("0/2 * * * * ?");
        return cronTriggerFactory;
    }

    /**
     * 3、创建scheduler对象
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(/*SimpleTriggerFactoryBean*/CronTriggerFactoryBean triggerFactory,
                                                                                 QuartzAdaptableJobFactory quartzAdaptableJobFactory) {
        SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
        // 关联trigger
        schedulerFactory.setTriggers(triggerFactory.getObject());
        schedulerFactory.setJobFactory(quartzAdaptableJobFactory);
        return schedulerFactory;
    }
}
